package com.sgb.kjwl.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;

import com.alibaba.android.arouter.launcher.ARouter;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.lease.CompanyInfoEntity;
import com.sgb.kjwl.model.entity.self.UserAccount;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.activity.self.AddCarInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.logistics.AddCarActivity;
import com.sgb.kjwl.view.ui.activity.transport.CargoQuotationActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayBiddingOrderActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayGeneralQuotationForCompanyActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayGeneralQuotationOrderActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayGoodsOrderActivity;
import com.sgb.link.router.PathLogistics;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.sgb.member.ui.activity.PersonInviteJoinActivity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

/**
 * @author: 杨畔
 * @date: 2021/8/17 12:25
 * @Description: 物流权限判断工具类
 */
public class LogisticsPermissionHelper {
    //订单类型 0:接单 1:报价 2:竞价接单 3:普通报价
    private final int TYPE_ORDER = 0;
    private final int TYPE_QUOTE = 1;
    private final int TYPE_QUOTE_ORDER = 2;
    private final int TYPE_ORDER_QUOTE = 3;

    private LogisticsPermissionHelper() {
    }

    private static class Single {
        private static final LogisticsPermissionHelper INSTANCE = new LogisticsPermissionHelper();
    }

    public static LogisticsPermissionHelper getInstance() {
        return Single.INSTANCE;
    }

    //-------------------------------接单/报价-------------------------------------------------------

    /**
     * 普通货源接单权限判断
     *
     * @param no            接单货源no
     * @param goodsTerminal 接单货源的货主身份
     * @param msgFee        货源信息费
     */
    public void checkPermissionToOrder(Context context, String no, int goodsTerminal, String msgFee) {
        //判断登录
        if (UserOperating.getInstance().isNotLogged(context)) {
            return;
        }
        //判断实名
        if (!UserOperating.getInstance().isAuthRealName()) {
            shopAuthRealNameDialog(context);
            return;
        }
       /* //判断是否是个人
        if (!UserOperating.getInstance().isPersonal()) {
            DialogHelper.showAuthenDialog(context, 2);
            return;
        }*/
        //在当前企业下是否有【邀请】权限
        if (UserOperating.getInstance().isCompany()) {
            if (!PermissionCheckUtil.hasCompanyPermission(PermissionCheckUtil.KEY_CHEZHUBAOJIA)) {
                showCompanyDialog(context, String.format("%s未授予您接单/报价权限。建议您联系管理员分配权限",
                        DefaultUtil.getMaxLengthText(UserOperating.getInstance().getTeamOrCompanyName(), 4)));
                return;
            }
        }
        if (UserOperating.getInstance().isPersonal()) {
            //判断是否认证司机
            if (!UserOperating.getInstance().isAuthDriver()) {
                showAuthDriverDialog(context);
                return;
            }
            //判断是否认证有车辆
            if (!UserOperating.getInstance().hasCar()) {
                showAddCarDialog(context);
                return;
            }
            //判断是否需要完善车辆信息，只有一辆车的时候才检测
            checkCarInfo(context, no, goodsTerminal, msgFee, TYPE_ORDER);
        }else {
            checkAnotherPermission(context, no, goodsTerminal, msgFee, TYPE_ORDER);
        }
    }

    /**
     * 竞价货源报价权限判断
     *
     * @param no            接单货源no
     * @param goodsTerminal 接单货源的货主身份
     * @param msgFee        货源信息费
     */
    public void checkPermissionToQuote(Context context, String no, int goodsTerminal, String msgFee) {
        //判断登录
        if (UserOperating.getInstance().isNotLogged(context)) {
            return;
        }
        //判断实名
        if (!UserOperating.getInstance().isAuthRealName()) {
            shopAuthRealNameDialog(context);
            return;
        }
        //报价不需要切换司机身份，企业/团队也可以参与报价
        if (!UserOperating.getInstance().isPersonal()) {
            //企业/团队报价权限判断
            checkQuoteInfo(context, no, TYPE_QUOTE);
            return;
        }
        //司机身份权限判断
        //判断是否认证司机
        if (!UserOperating.getInstance().isAuthDriver()) {
            showAuthDriverDialog(context);
            return;
        }
        //判断是否认证有车辆
        if (!UserOperating.getInstance().hasCar()) {
            showAddCarDialog(context);
            return;
        }
        //判断是否需要完善车辆信息，只有一辆车的时候才检测
        checkCarInfo(context, no, goodsTerminal, msgFee, TYPE_QUOTE);
    }

    /**
     * 竞价货源接单权限判断
     *
     * @param no            接单货源no
     * @param goodsTerminal 接单货源的货主身份
     * @param msgFee        货源信息费
     */
    public void checkPermissionToQuoteOrder(Context context, String no, int goodsTerminal, String msgFee) {
        //判断登录
        if (UserOperating.getInstance().isNotLogged(context)) {
            return;
        }
        //判断实名
        if (!UserOperating.getInstance().isAuthRealName()) {
            shopAuthRealNameDialog(context);
            return;
        }
        //报价不需要切换司机身份，企业/团队也可以参与报价
        if (!UserOperating.getInstance().isPersonal()) {
            //企业/团队接单判断
            checkQuoteInfo(context, no, TYPE_QUOTE_ORDER);
            return;
        }
        //司机身份权限判断
        //判断是否认证司机
        if (!UserOperating.getInstance().isAuthDriver()) {
            showAuthDriverDialog(context);
            return;
        }
        //判断是否认证有车辆
        if (!UserOperating.getInstance().hasCar()) {
            showAddCarDialog(context);
            return;
        }
        //判断是否需要完善车辆信息，只有一辆车的时候才检测
        checkCarInfo(context, no, goodsTerminal, msgFee, TYPE_QUOTE_ORDER);
    }

    /**
     * 普通货源报价权限判断
     *
     * @param no            接单货源no
     * @param goodsTerminal 接单货源的货主身份
     * @param msgFee        货源信息费
     */
    public void checkPermissionToOrderQuote(Context context, String no, int goodsTerminal, String msgFee) {
        //判断登录
        if (UserOperating.getInstance().isNotLogged(context)) {
            return;
        }
        //判断实名
        if (!UserOperating.getInstance().isAuthRealName()) {
            shopAuthRealNameDialog(context);
            return;
        }
       /* //判断是否是个人
        if (!UserOperating.getInstance().isPersonal()) {
            DialogHelper.showAuthenDialog(context, 2);
            return;
        }*/
        //在当前企业下是否有【邀请】权限
        if (UserOperating.getInstance().isCompany()) {
            if (!PermissionCheckUtil.hasCompanyPermission(PermissionCheckUtil.KEY_CHEZHUBAOJIA)) {
                showCompanyDialog(context, String.format("%s未授予您接单/报价权限。建议您联系管理员分配权限",
                        DefaultUtil.getMaxLengthText(UserOperating.getInstance().getTeamOrCompanyName(), 4)));
                return;
            }
        }
        //报价不需要切换司机身份，企业/团队也可以参与报价
        if (!UserOperating.getInstance().isPersonal()) {
            //企业/团队报价权限判断
            checkQuoteInfo(context, no, TYPE_ORDER_QUOTE);
            return;
        }
        //判断是否认证司机
        if (UserOperating.getInstance().isPersonal()) {
            if (!UserOperating.getInstance().isAuthDriver()) {
                showAuthDriverDialog(context);
                return;
            }
            //判断是否认证有车辆
            if (!UserOperating.getInstance().hasCar()) {
                showAddCarDialog(context);
                return;
            }
            //判断是否需要完善车辆信息，只有一辆车的时候才检测
            checkCarInfo(context, no, goodsTerminal, msgFee, TYPE_ORDER_QUOTE);
        }
    }

    /**
     * 检查报价信息（企业/团队报价权限判断）
     */
    private void checkQuoteInfo(Context context, String no, int orderType) {
        com.swgk.core.dialog.DialogHelper.showProgressDialog(context, "请求中...");
        NewAPIManager.getInstance().getLogisticsAPI().checkOffer(no, orderType == TYPE_QUOTE_ORDER ? 2 : 0)
                .enqueue(new ICallBack<BaseEntity>() {
                    @Override
                    public void onSuccess(BaseEntity data) {
                        if ("200".equals(data.getCode())) {
                            jumpToOrder(context, no, orderType);
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity> call, Throwable t) {
                    }

                    @Override
                    public void onFailureWithEntity(BaseEntity data) {
                        if ("230".equals(data.getCode())) {
                            //企业内重复报价
                            showRepeatQuoteDialog(context, no, data.getMsg(), orderType);
                        } else if ("235".equals(data.getCode())) {
                            //已经有报价或接单 不能接单
                            showTipDialog(context, data.getMsg());
                        } else if ("240".equals(data.getCode())) {
                            //报价已同意
                            showTipDialog(context, data.getMsg());
                        }
                    }
                });
    }

    /**
     * 检查车辆信息
     *
     * @param orderType 订单类型 0:接单 1:报价 2:竞价接单
     */
    private void checkCarInfo(Context context, String no, int goodsTerminal, String msgFee, int orderType) {
        com.swgk.core.dialog.DialogHelper.showProgressDialog(context, "请求中...");
        APIManager.getInstance().getDriverAPI().getCarInfo().enqueue(new ICallBack<BaseEntity<List<CarInfo>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CarInfo>> data) {
                if (ArrayUtil.isNotNullAndEmpty(data.getData())) {
                    //判断是否需要完善车辆信息，只有一辆车的时候才检测
                    boolean isNeedComplete = false;
                    if (data.getData().size() == 1 && data.getData().get(0).getIsComplete() == 0) {
                        isNeedComplete = true;
                    }
                    if (isNeedComplete) {
                        CarInfo carInfo = data.getData().get(0);
                        showCompleteCarDialog(carInfo, context);
                    } else {
                        checkAnotherPermission(context, no, goodsTerminal, msgFee, orderType);
                    }
                }
            }
        });
    }

    /**
     * 检查其他所需权限
     */
    private void checkAnotherPermission(Context context, String no, int goodsTerminal, String msgFee, int orderType) {
        /*if (orderType==2||orderType==0) {
            //判断用户是否开通资金账户
            if (!UserOperating.getInstance().isOpenFundAccount()) {
                showOpenFundAccountDialog(context);
                return;
            }
        }*/
        //检查信息费
        if (!TextUtils.isEmpty(msgFee)) {
            double messagePrice = NumberUtil.convertToDouble(msgFee);
            if (messagePrice != 0) {
                if (orderType==3||orderType==1){
                    //报价时不判断资金账户是否开通
                    jumpToOrder(context, UserOperating.getInstance().isPersonal(), no, orderType);
                }else {
                    checkGoodsFundAccount(context, no, goodsTerminal, orderType);
                }
            } else {
                jumpToOrder(context, UserOperating.getInstance().isPersonal(), no, orderType);
            }
        } else {
            MToast.showToast(context, "信息费为空");
        }
    }

    /**
     * 检查货源发布人资金账户
     */
    private void checkGoodsFundAccount(Context context, String no, int goodsTerminal, int orderType) {
        Map<String, Object> map = new HashMap<>();
        map.put("goodsSourceNo", no);
        com.swgk.core.dialog.DialogHelper.showProgressDialog(context, "请求中...");
        APIManager.getInstance().getDriverAPI().confirmFundAccount(map).enqueue(new ICallBack<BaseEntity<UserAccount>>() {
            @Override
            public void onSuccess(BaseEntity<UserAccount> data) {
                UserAccount userAccount = data.getData();
                if (!userAccount.isIsDriverOpenFundsAccount() && goodsTerminal == 2) {//货源货主团队没开通资金账户
                    showGoodsOwnerFundAccountDialog(context, orderType);
                } else if (!userAccount.isIsOpenFundsAccount() && goodsTerminal == 1) {//货源货主企业没开通资金账户
                    showGoodsOwnerFundAccountDialog(context, orderType);
                } else if (!userAccount.isIsDriverOpenFundsAccount() && goodsTerminal == 3) {//个人货源资金账户
                    showGoodsOwnerFundAccountDialog(context, orderType);
                } else {
                    jumpToOrder(context, UserOperating.getInstance().isPersonal(), no, orderType);
                }
            }
        });
    }

    /**
     * 跳转默认无需再次检查竞价状态
     */
    private void jumpToOrder(Context context, String no, int orderType) {
        jumpToOrder(context, false, no, orderType);
    }

    /**
     * 根据订单类型跳转对应接单页
     *
     * @param isNeedCheckQuoteAgain 是否需要再次检查竞价状态（司机接单报价时需要在最后判断是否有接单或报价）
     * @param no                    货源no
     * @param orderType             订单类型
     */
    private void jumpToOrder(Context context, boolean isNeedCheckQuoteAgain, String no, int orderType) {
        if (orderType == TYPE_ORDER) {
            //普通货源接单
            if (!UserOperating.getInstance().isPersonal()){
                ARouter.getInstance().build(PathLogistics.GroupPayGoodsOrderActivity)
                        .withString(RouterKey.NO, no)
                        .navigation();
            }else {
                ARouter.getInstance().build(PathLogistics.DriverPayGoodsOrderActivity)
                        .withString(RouterKey.NO, no)
                        .navigation();
                // PayGoodsOrderActivity.start(context, no, 0);
            }
        } else if (orderType == TYPE_QUOTE) {
            //竞价报价
            if (isNeedCheckQuoteAgain) {
                checkQuoteInfo(context, no, orderType);
            } else {
                CargoQuotationActivity.startForResult((Activity) context, no, false, UserOperating.getInstance().isPersonal(), "");
            }
        } else if (orderType == TYPE_QUOTE_ORDER) {
            //竞价接单
            if (isNeedCheckQuoteAgain) {
                checkQuoteInfo(context, no, orderType);
            } else {
                PayBiddingOrderActivity.startForResult((Activity) context, no, false, UserOperating.getInstance().isPersonal(), "");
            }
        } else if (orderType == TYPE_ORDER_QUOTE) {
            //普通货源报价
            if (!UserOperating.getInstance().isPersonal()){
                //TODO 去新的企业/团队报价界面
                PayGeneralQuotationForCompanyActivity.startForResult((Activity) context, no, false, true, "");
            }else {
                PayGeneralQuotationOrderActivity.startForResult((Activity) context, no, false, true, "");
            }
        }
    }

    /**
     * 实名认证弹窗
     */
    private void shopAuthRealNameDialog(Context context) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content("您当前未实名认证，是否立即认证？")
                .cancel("取消")
                .confirm("确定")
                .cancelable(false)
                .confirmCallback(v -> AuthActivity3.start(context))
                .show();
    }

    /**
     * 司机认证弹窗
     */
    private void showAuthDriverDialog(Context context) {
        new RoundDialog.Builder(context)
                .title("温馨提示")
                .content("您当前未进行司机认证，请前往\n" +
                        "认证中心完成认证后，再接单！")
                .cancel("取消")
                .confirm("去认证")
                .confirmColor(Color.parseColor("#5792FD"))
                .confirmCallback(v -> AuthActivity3.start(context))
                .show();
    }

    /**
     * 添加车辆提示
     */
    private void showAddCarDialog(Context context) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content("您未认证驾驶车辆，需添加车辆，才可办理业务。")
                .cancel("取消")
                .confirm("去添加")
                .confirmCallback(v -> AddCarActivity.start(context))
                .show();
    }

    /**
     * 完善车辆提示
     */
    private void showCompleteCarDialog(CarInfo carInfo, Context context) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content(String.format("请先完善%s的车辆信息", carInfo.getCarNumber()))
                .cancel("暂不完善")
                .confirm("确定")
                .confirmCallback(v -> {
                    Intent intent = new Intent(context, AddCarInfoActivity.class);
                    intent.putExtra("carNo", NumberUtil.convertToLong(carInfo.getNo()));
                    context.startActivity(intent);
                })
                .show();
    }

    /**
     * 资金账户提示 自己是否开通
     */
    private void showOpenFundAccountDialog(Context context) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content("开通在线收款账户后\n可使用此功能")
                .cancel("知道了")
                .confirm("前往开户")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(toh5 -> UserOperating.getInstance().jumpToOpenAccount(context))
                .show();
    }

    /**
     * 货主未开通资金账户提示
     */
    private void showGoodsOwnerFundAccountDialog(Context context, int orderType) {
        String tip = "";
        if (orderType == TYPE_ORDER) {
            tip = "货主未开通收款账户，无法接单";
        } else if (orderType == TYPE_QUOTE) {
            tip = "货主未开通收款账户，无法报价";
        } else if (orderType == TYPE_QUOTE_ORDER) {
            tip = "货主未开通收款账户，无法接单";
        }
        new RoundDialog.Builder(context)
                .title("提示")
                .content(tip)
                .singleBtn(true)
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .show();
    }

    /**
     * 重复报价提示
     */
    private void showRepeatQuoteDialog(Context context, String no, String msg, int orderType) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content(DefaultUtil.getString(msg))
                .confirm("确定")
                .cancel("取消")
                .confirmCallback(v -> jumpToOrder(context, no, orderType))
                .show();
    }

    /**
     * 统一‍提示弹窗
     */
    private void showTipDialog(Context context, String msg) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content(DefaultUtil.getString(msg))
                .singleBtn(true)
                .confirm("确定")
                .show();
    }
    /**
     * 企业权限提示
     */
    private void showCompanyDialog(Context context, String msg){
        new RoundDialog.Builder(context)
                .title("提示")
                .content(DefaultUtil.getString(msg))
                .singleBtn(true)
                .confirm("我知道了")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .show();
    }

    //-------------------------------邀请-------------------------------------------------------

    /**
     * 邀请权限判断
     *
     * @param inviteTerminal 被邀请人身份 0个人 1企业 2团队
     * @param no             被邀请人No(个人no/团队no/企业no)
     */
    public void checkPermissionToInvite(Context context, String no, int inviteTerminal) {
        //判断登录
        if (UserOperating.getInstance().isNotLogged(context)) {
            return;
        }
        //团队用户
        if (UserOperating.getInstance().isTeam()) {
            showTipDialog(context, "团队邀请会员功能暂未开放");
            return;
        }
        if (UserOperating.getInstance().isPersonal()) {
            //个人用户
//            if (inviteTerminal != 1) {
//                showTipDialog(context, "暂不支持邀请团队/组织/个人");
//                return;
//            }
            //打开不需要审批的邀请会员表单页面
            toInviteCompany(context, no, inviteTerminal);
        } else if (UserOperating.getInstance().isCompany()) {
            //企业用户
//            if (inviteTerminal != 1) {
//                showTipDialog(context, "暂不支持邀请团队/组织/个人");
//                return;
//            }
            //在当前企业下是否有【邀请】权限
            if (!PermissionCheckUtil.hasCompanyPermission(PermissionCheckUtil.KEY_YAOQINGGUANLI)) {
                showTipDialog(context, String.format("%s未授予您邀请会员的权限，请联系管理员分配权限",
                        DefaultUtil.getMaxLengthText(UserOperating.getInstance().getTeamOrCompanyName(), 4)));
                return;
            }
            //该企业是否要求【邀请】会员需要审批，邀请表单页自行判断了
            toInviteCompany(context, no, inviteTerminal);
        }
    }

    /**
     * 通过企业no获取企业信息
     *
     * @param inviteTerminal 被邀请人身份 0个人 1企业 2团队
     * @param companyNo      被邀请人企业No
     */
    private void toInviteCompany(Context context, String companyNo, int inviteTerminal) {
        com.swgk.core.dialog.DialogHelper.showProgressDialog(context, "加载中...").setCanceledOnTouchOutside(false);
        if (TextUtils.isEmpty(companyNo)){
            LogUtil.e("error", "企业NO为空，请求接口会导致接口响应失败（code = 500）");
            return;
        }
        NewAPIManager.getInstance().getLogisticsAPI().getCompanyDetail(companyNo).enqueue(new ICallBack<BaseEntity<CompanyInfoEntity>>() {
            @Override
            public void onSuccess(BaseEntity<CompanyInfoEntity> data) {
                CompanyInfoEntity entity = data.getData();
                QualityMemberBean memberBean = new QualityMemberBean();
                memberBean.setCompanyId(entity.getId());
                memberBean.setCompanyNo(companyNo);
                memberBean.setCompanyName(entity.getName());
                memberBean.setAddress(entity.getAddress());
                if (inviteTerminal == 0) {
                    //邀请个人
                    memberBean.setNo(entity.getNo());
                    PersonInviteJoinActivity.start((Activity) context, memberBean, false);
                } else if (inviteTerminal == 1) {
                    //邀请企业
                    memberBean.setServiceType(entity.getServiceType());
                    memberBean.setServiceTypeName(entity.getServiceType());
                    memberBean.setProvinceNo(entity.getProvinceNo());
                    memberBean.setCityNo(entity.getCityNo());
                    memberBean.setDistrictNo(entity.getDistrictNo());
                    MemberInviteJoinActivity.start((Activity) context, memberBean);
                }
            }
        });
    }
}
